package com.example.base.security.jwt;

import com.alibaba.fastjson.JSONObject;
import com.example.base.security.SecurityUtil;
import com.example.base.security.SysUser;
import com.example.base.security.domain.SelfUserEntity;
import com.example.base.security.domain.SysUserEntity;
import com.example.base.security.domain.SysUserToken;
import com.example.base.security.service.SysUserTokenService;
import com.example.base.utils.CookieUtils;
import com.example.base.utils.SpringContextUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.util.StringUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author Xiongx
 * @version 1.0
 * @date 2021/6/11 15:13
 * @since JDK 1.8
 */
@Slf4j
public class JWTAuthenticationTokenFilter extends BasicAuthenticationFilter {

    public JWTAuthenticationTokenFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 获取请求头中JWT的Token
        String token="";
        String tokenHeader = request.getHeader(JWTConfig.tokenHeader);
        if(tokenHeader!=null){
            // 截取JWT前缀
            token = tokenHeader.replace(JWTConfig.tokenPrefix, "");
        }
        log.info("token:{}",token);
        if(tokenHeader==null){
            Cookie[] cookies=request.getCookies();
            Cookie cookie= CookieUtils.getCookieByName(cookies,JWTConfig.tokenHeader);
            if(cookie != null){
                token = cookie.getValue();
                token=token.replace(JWTConfig.tokenPrefix,"");
            }
        }
        if (org.apache.commons.lang3.StringUtils.isNotBlank(token)) {
            try {
                // 解析JWT
                Claims claims = Jwts.parser()
                        .setSigningKey(JWTConfig.secret)
                        .parseClaimsJws(token)
                        .getBody();
                // 使用签发时间
                Date date=claims.getIssuedAt();
                Date current=new Date();
                log.info("有效期{}",current.getTime() - date.getTime());
                //现在的时间减去签发时间
                if((current.getTime() - date.getTime()) > 10000){
                    SysUserTokenService userTokenService= SpringContextUtils.getBean(SysUserTokenService.class);
                    SysUserToken userToken=userTokenService.getMuserTokenByToken(JWTConfig.tokenPrefix+token);
                    if(userToken != null && userToken.getIsEnable()){
                        JWTTokenUtil.tokenPass(token,claims,response);
                    }
                }else {
                    JWTTokenUtil.tokenPass(token,claims,response);
                }
            } catch (ExpiredJwtException e){
                log.info("Token过期");
            } catch (Exception e) {
                log.info("Token无效");
            }
        }
        filterChain.doFilter(request, response);
    }



}
